package com.crape.account.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.crape.account.bo.IAccountBO;
import com.crape.account.bo.IAccountHelperBO;
import com.crape.common.enums.ResultType;
import com.crape.common.enums.StatusType;
import com.crape.common.model.Account;
import com.crape.common.model.AccountInfo;
import com.crape.common.model.Subject;
import com.crape.common.utils.RegisterCheck;
import com.crape.topic.bo.ISubjectBO;

@Controller
public class AuthController {

    private IAccountBO       accountBOImpl;
    private IAccountHelperBO accountHelperBOImpl;
    private ISubjectBO  SubjectBOImpl;

    @Autowired
    public void setAccountBOImpl(IAccountBO accountBOImpl) {
        this.accountBOImpl = accountBOImpl;
    }

    @Autowired
    public void setAccountHelperBOImpl(IAccountHelperBO accountHelperBOImpl) {
        this.accountHelperBOImpl = accountHelperBOImpl;
    }

    @Autowired
    public void setSubjectBOImpl(ISubjectBO SubjectBOImpl) {
        this.SubjectBOImpl = SubjectBOImpl;
    }

    @RequestMapping("/auth/register.jsp")
    public String register(HttpServletRequest request, ModelMap modelMap, Account account) {
        modelMap.put("account", account);
        if (this.validate(modelMap, account)) {
            String sessionCode = (String) request.getSession().getAttribute("validateCode");
            if (null == sessionCode) {
                modelMap.put("errorMessage", "会话已过期，请重新登录!");
                return "/auth/register.html";
            }
            if (!account.getCheckcode().toUpperCase().equalsIgnoreCase(sessionCode)) {
                modelMap.put("errorMessage", "验证码不正确！");
                return "/auth/register.html";
            }
            accountBOImpl.addAccount(account);
        } else {
            return "/auth/register.html";
        }
        return "/auth/valideEmail.html";
    }

    @RequestMapping("/auth/oncemore.jsp")
    public String oncemore(ModelMap modelMap, String username) {
        Account account = accountBOImpl.validateOnceMore(username);
        modelMap.put("account", account);
        return "/auth/valideEmail.html";
    }

    @RequestMapping("/auth/verify.jsp")
    public String verify(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap,
                         AccountInfo account) {
        List<AccountInfo> acctlist = accountBOImpl.getAccountInfos(account);
        if (acctlist == null || acctlist.isEmpty()) {
            modelMap.put("message", "验证信息已过期！");
            modelMap.put("username", account.getUsername());
            return "/auth/verify.html";
        }
        AccountInfo acct = acctlist.get(0);
        accountBOImpl.updateAccountStatus(acct.getAccountid(), StatusType.ok.getCode());
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setAccountid(acct.getAccountid());
        accountBOImpl.updateInfo(accountInfo);
        modelMap.put("account", acct);
        accountHelperBOImpl.setupAccountInfo(request, response, acct);
        return "/auth/verify.html";
    }

    @RequestMapping("/auth/validateEmail.json")
    public ModelAndView validateEmail(String email) {
        ModelAndView mv = new ModelAndView();
        try {
            boolean isEmail = RegisterCheck.isEmail(email);
            if (!isEmail) {
                mv.addObject("flag", ResultType.FAILURE.getCode());
                mv.addObject("message", "邮箱格式有问题，请修改");
                return mv;
            }
            Account account = accountBOImpl.getAccountByEmail(email);
            mv.addObject("data", account);
            if (account != null) {
                mv.addObject("message", "该邮箱已注册");
                mv.addObject("flag", ResultType.FAILURE.getCode());
                return mv;
            }
            mv.addObject("flag", ResultType.SUCCESS.getCode());
            return mv;
        } catch (Exception e) {
            mv.addObject("message", e.getMessage());
            mv.addObject("flag", ResultType.FAILURE.getCode());
            return mv;
        }
    }

    @RequestMapping("/auth/validateUsername.json")
    public ModelAndView validateUsername(String username) {
        ModelAndView mv = new ModelAndView();
        Account account = accountBOImpl.getAccountByUsername(username);
        mv.addObject("data", account);
        if (account != null) {
            mv.addObject("flag", 0);
            mv.addObject("message", "用户名已经被占用");
            return mv;
        }
        mv.addObject("flag", ResultType.SUCCESS.getCode());
        return mv;
    }

    private boolean validate(ModelMap modelMap, Account account) {
        if (account == null) {
            modelMap.put("email_info", "邮箱信息为空");
            return false;
        }
        String email = account.getEmail();
        if (email == null || email.isEmpty()) {
            modelMap.put("email_info", "请输入邮箱");
            return false;
        }
        boolean isEmail = RegisterCheck.isEmail(email);
        if (!isEmail) {
            modelMap.put("email_info", "邮箱格式有问题");
            return false;
        }
        Account accountEmail = accountBOImpl.getAccountByEmail(account.getEmail());
        if (accountEmail != null) {
            modelMap.put("email_info", "该邮箱已注册");
            return false;
        }

        String username = account.getUsername();
        if (username == null || username.isEmpty()) {
            modelMap.put("username_info", "请输入用户名");
            return false;
        }
        Account accountName = accountBOImpl.getAccountByUsername(username);
        if (accountName != null) {
            modelMap.put("username_info", "该用户名已经被占用");
            return false;
        }

        String password = account.getPassword();
        if (password == null || password.isEmpty()) {
            modelMap.put("password_info", "请输入密码");
            return false;
        }
        String confirm = account.getConfirm();
        if (confirm == null || confirm.isEmpty()) {
            modelMap.put("confirm_info", "请输入确认密码");
            return false;
        }
        if (!password.equals(confirm)) {
            modelMap.put("confirm_info", "确认密码不一致，请重新输入");
            return false;
        }
        Boolean isAgreement = account.getIsAgreement();
        if (isAgreement == null || !isAgreement) {
            modelMap.put("errorMessage", "请接受瓜朋网服务使用协议");
            return false;
        }
        return true;
    }

    @RequestMapping("/auth/subjects.jsp")
    public String subjects(ModelMap modelMap) {
        List<Subject>  subjects = SubjectBOImpl.getAllSubjects(0, 20);
        modelMap.put("subjects", subjects);
        return "/auth/subjects.html";
    }

    @RequestMapping("/auth/darrens.jsp")
    public String darrens(ModelMap modelMap) {
        List<AccountInfo> darrens = accountBOImpl.getAllDarrens(0, 20);
        modelMap.put("darrens", darrens);
        return "/auth/darrens.html";
    }

}
